package com.lemon.components.ant.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.StringWriter;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
/**
 * 模版类，使用FreeMarker模版引擎<#FREEMARKER>
                                                
                                                                  
           .~;x3js7LLZllPl9yyI="`
        .=yGdMbMJJJJ@WhN0&|mBm|BAj=.
      .=pUhUQMJ0O&OO#%W@O|BpSSnXpm$/".
   .` vWWWWW#hQbJdVQWWWhQMd$||mBBBB&m=
   .. E%WWWWWW#hQ@UWWWWWWhU@bMJd0O||J<
     .rhWWWWWWW###WWWWWWWW#hU@NbbM0$0Se;`.
    .  rWWW##hhh#WWWWWWWWhhHUQDNMV$$&m0|}vx<r"`.
       .jW#hHUUUHhWWW%WWhHUUQQ@bJ0|QQd00VddUhUQUN(r`
         eWhHHHUUUHWW%%#HUUUUQQNJ$VHUQDbJMd|B0Jbh%%hx
         .yW###hUUhWWhQWhUUUQQQNVJh##WhVJJNQJDQbdW%%%r
           aWWhUUUH#Wh<hWHUQQ@NMOh%%WhNJUQQQU@UUW%%%%0.
           .=Q#UUHHhWWUWWhUQQ@MMmb%%%%%WWWWWWW%%%%%%%B.
             rH#UHHh#W%WWhUUQDNC=PW%%%%%%%%%%%%%%%%%%M;
              r#hhhh#WWWW#HUQ@QI`IW%%%%%%%%%%%%%%%%%%WE'
               8WW#hhWWWWhhhhUUa`vW%%%%%%%%%%%%%%%%%%h2"
              :@%WWWhhWWWWWWhM0O3vW%%%%%%%%%%%%%%%%%%@j=.
             ;Q%WhhhUhUx)WWWUM&$V|$h%%%%%%%%%%%%%%%%W|r.
            `0%#U@DNQ0=. =b%WUbd||pSW%%%%%%%W%%%%%%W|2_
           `9%WUbbbMNr    "&%WUbV$|B0W%%%%%%%%%%W%%N;~
           `m%hDMMMNn_     :BWWUbV$|B5@%%W%%%%%%W%%%!
           `|WUNMMMNx.      .jWWh@V|0l"o%hW%%%W%%QW%Nr
           `mWUDbMNE          rQWhbO|Jr rhWW%%%W%#@%3_
           .6W@bJJV=           =JWUM$d/` r=0%WW%hWUm`
           `)WNMJM}:            -8#QJ|m;   ~<BfMWbQ"
           _3#bJdNx              _AhQJJj     . .r!=
           .=UNVd@=               ~hhUNMy_
           .IhMJM@1.              .[Wh#@b)=_
           :0hVMbM&r.             .~SUHUbNn".';
"x3<x="~'-~SWbd$OOMb}x;"            =bJMNbNpI4PPPPP
 * @author jlcon
 *
 */
public class TemplateUtil {
	
	private static Logger logger = LoggerFactory.getLogger(TemplateUtil.class);
	
	private static TemplateUtil templateUtil = null;
	
	public static TemplateUtil getInstance(String template){
		if(templateUtil == null){
			templateUtil = new TemplateUtil(template);
			return templateUtil;
		} else {
			return templateUtil;
		}
	}
	
	public static void main(String[] args) {
		TemplateUtil templateUtil = new TemplateUtil("D:/workspace/myboot/src/main/resources/code/maven-project-template");
		System.out.println(templateUtil.print("/html/boss/console.html", templateUtil));
	}
	
	private File directoryForTemplateLoading;
	
	private Configuration cfg;
	
	private TemplateUtil(){
		
	}
	
	private TemplateUtil(String template){
		try {
			directoryForTemplateLoading = new File(template);
			cfg = new Configuration(Configuration.VERSION_2_3_26);
			cfg.setDirectoryForTemplateLoading(directoryForTemplateLoading);
			cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
			cfg.setDateFormat("yyyy-MM-dd");
			cfg.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
			cfg.setDefaultEncoding("utf-8");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void build(String tpl, String outputfile, Object params) {
		build(tpl,outputfile,params,true);
	}
	/**
	 * 
	 * <font size="3" color="red">通过模版生成文件</font><br>
	 * <ol>
	 * <li>指定模版目录</li>
	 * <li>指定模版文件相对路径</li>
	 * <li>指定模版文件输出绝对路径</li>
	 * <li>参数可选</li>
	 * </ol>
	 * @param template 模版目录
	 * @param tpl 模版路径
	 * @param outputfile 输出文件
	 * @param params freemarker参数
	 */
	public void build(String tpl, String outputfile, Object params,boolean overwrite) {
		try {
			Template temp = cfg.getTemplate(tpl, Locale.CHINA, "utf-8");
			File file = new File(outputfile);
			if (file.exists()) {
				if(overwrite) {
					logger.warn("文件存在，覆盖！...{}",outputfile);
				} else {
					logger.warn("文件存在，跳过！...{}",outputfile);
					return;
				}
			} else {
				logger.warn("文件{}不存在，创建!",file.getAbsolutePath());
				File folder = new File(file.getParent());
				if(!(folder.exists())) {
					folder.mkdirs();
				}
			}
			FileWriter fileWriter = new FileWriter(file);
			BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
			temp.process(params, bufferedWriter);
			bufferedWriter.flush();
			fileWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void buildFromString(String ftlContent,String outputfile, Object params) {
		buildFromString(ftlContent,outputfile, params, true);
	}
	
	public void buildFromString(String ftlContent,String outputfile, Object params,boolean overwrite) {
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("myTemplate", ftlContent);
        cfg.setTemplateLoader(stringLoader);
        try {
        	File file = new File(outputfile);
			if (file.exists()) {
				if(overwrite) {
					logger.warn("文件存在，覆盖！...{}",outputfile);
				} else {
					logger.warn("文件存在，跳过！...{}",outputfile);
					return;
				}
			} else {
				logger.warn("文件{}不存在，创建!",file.getAbsolutePath());
				File folder = new File(file.getParent());
				if(!(folder.exists())) {
					folder.mkdirs();
				}
			}
			FileWriter fileWriter = new FileWriter(file);
			BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
			Template temp = cfg.getTemplate("myTemplate","utf-8");
			temp.process(params, bufferedWriter);
			bufferedWriter.flush();
			fileWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public File getDirectoryForTemplateLoading() {
		return directoryForTemplateLoading;
	}
	
	public String parseHtml2Ftl(File html) {
		try (BufferedReader reader = new BufferedReader(new FileReader(html))){
			StringBuffer sb = new StringBuffer();
			String tmp = null;
			while((tmp = reader.readLine())!=null) {
				sb.append(tmp);
				sb.append("\n");
			}
			return sb.toString()
					.replaceAll("<#if", "<\\$\\{r'#'\\}if")
					.replaceAll("<@", "<\\${r\"@\"}");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String print(String tpl, Object params) {
		try {
			Template temp = cfg.getTemplate(tpl);
			StringWriter stringWriter = new StringWriter();
			BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
			temp.process(params, bufferedWriter);
			bufferedWriter.flush();
			String tmp = stringWriter.toString();
			stringWriter.close();
			return tmp;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public void setDirectoryForTemplateLoading(File directoryForTemplateLoading) {
		this.directoryForTemplateLoading = directoryForTemplateLoading;
	}
}
